#include "MyLogger.hpp"
#include <log4cpp/FileAppender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include <iostream>
#include <memory>
#include <string.h>
#include <iostream>
#include <cstdarg>
using std::cout;
using std::endl;

namespace wd
{
MyLogger *MyLogger::_pInstance=nullptr;

MyLogger::MyLogger()
{
    //1.创建布局对象，自定义格式
    PatternLayout *layout=new PatternLayout();
    // 简化格式，文件名和行号已经在日志方法中添加
    layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S.%l} [%p] - %m%n");
    
    //2.创建Appender输出server.log
    Appender *fileAppender=new FileAppender("fileAppender","log_file");
    fileAppender->setLayout(layout);
    
    //3.创建控制台Appender输出out
    Appender *consoleAppender=new OstreamAppender("console",&cout);
    consoleAppender->setLayout(layout);
    
    //4.创建日志类别并添加Appender
    _category=&Category::getInstance("ServerLogger");
    _category->addAppender(fileAppender);
    _category->addAppender(consoleAppender);
    
    //5.设置日志级别
    _category->setPriority(Priority::DEBUG);
}

MyLogger::~MyLogger()
{
    Category::shutdown();
}

MyLogger *MyLogger::getInstance()
{
   if(!_pInstance)
   {
       _pInstance=new MyLogger();
   }
   return _pInstance;
}

void MyLogger::destory()
{
    if(_pInstance)
    {
        delete _pInstance;
        _pInstance=nullptr;
    }
}

void MyLogger::warn(const char * file,int line,const char * func,const char *msg)
{
    _category->warn("[%s:%d] %s: %s", file, line, func, msg);
}

void MyLogger::error(const char * file,int line,const char * func,const char *msg)
{
    _category->error("[%s:%d] %s: %s", file, line, func, msg);
}

void MyLogger::debug(const char * file,int line,const char * func,const char *msg)
{
    _category->debug("[%s:%d] %s: %s", file, line, func, msg);
}

void MyLogger::info(const char * file,int line,const char * func,const char *format, ...)
{
    char buffer[1024];
    va_list args;
    va_start(args, format);
    vsnprintf(buffer, sizeof(buffer), format, args);
    va_end(args);

    // 使用格式化后的字符串调用实际的日志记录
    _category->info("[%s:%d %s] %s", file, line, func, buffer);
}
}

















































































